package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sessions")
public class SessionController {
    @Autowired
    private IUserService userService;

    /*
        用户登录:
        资源:/sessions
        动作:POST
        参数:email=xx&password=xx


     */
    @PostMapping
    public Object login(String email, String password) {
        JSONResult result = new JSONResult();
        try {
            User u = userService.login(email, password);
            result.setObj(u);
            //把当前登录成功的用户存入session
            UserContext.setCurrentUser(u);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /*
        用户注销
        资源:/sessions
        动作:DELETE
        参数:
     */
    @DeleteMapping
    public void logout(HttpSession session, HttpServletResponse resp) {
        session.invalidate();
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
